<style type="text/css">
.ui-dialog h2.errorLog {
    margin: 0 0 15px 0;
    color: #AA0004;
    font-size: 1.2em;
    font-weight: bold;
}
</style>

<div id="addMessages-cont" class="hidden">
    <form class="well form-inline margin-horisontal login" action="javascript:void(0);" method="POST" name="addMessagesForm" id="addMessagesForm">
    <h2 class="errorLog hidden"></h2>
    <fieldset>
        <label for="title">Заголовок</label>
        <input name="title" type="text"/>
        <label for="to_date">Дата</label>
        <input name="to_date" type="text" />
        <label for="text">Ваше сообщение</label>
        <textarea name="text" rows="5" placeholder="Ваше сообщение"></textarea>
    </fieldset>
    <div class="form-actions">
      <button type="submit" class="btn btn-primary" id="addMessagesForm-submit">
        <i class="icon-ok icon-white"></i>OK
      </button>
      <button type="reset" class="btn btn-danger" id="addMessagesForm-cancel">
        <i class="icon-remove icon-white"></i>
        Отменить
      </button>
    </div>
    </form>
</div>
<script type="text/javascript">

    dlg  = $('#addMessages-cont'),
    form = dlg.children('form');

    function mgsActionInit(data) {
        $('*[data-action]').each(function(){
            $(this).click(function(e){
                form.data({
                    action: $(this).data('action'),
                    a:      $(this).parents('li').data()
                });
                dlg.dialog('open');
            });
        });
    }

    function mgsDialogInit(data){
        var mgs = {
                title:    form.find('*[name=title]'),   // Заголовок
                to_date:  form.find('*[name=to_date]'),    // Дата
                text:     form.find('*[name=text]'), // Сообщение
            };

        mgs.all = $([]).add(mgs.title).add(mgs.to_date).add(mgs.text);

        dlg.dialog({
                    autoOpen:   false,
                    width:      350,
                    modal:      true,
                    draggable:  true,
                    resizable:  false,
                    stack:      true,
                    open: function(event, ui){
                        var a = form.data('a');
                        $(this).find('.errorLog').addClass('hidden');
                        switch (form.data('action')) {
                            case 'insert':
                                mgs.title.val('');
                                mgs.to_date.val('<?php print date('Y-m-d') ?>');
                                mgs.text.val('');
                                $(this).dialog('option', 'title',  'Добавить');
                                break;

                            case 'update':
                                mgs.title.val(a.title);
                                mgs.to_date.val(a.to_date);
                                mgs.text.val(a.text);
                                $(this).dialog('option', 'title',  'Правка:&ensp;' + a.title);
                                $(this).dialog('option', 'hieght',  'inherit');
                                break;

                            case 'delete':
                                $('.errorLog').removeClass('hidden').text(a.title);
                                mgs.all
                                    .add(form.find('fieldset'))
                                    .add(form.find('fieldset'))
                                    .addClass('hidden');
                                $(this).dialog('option', 'title',  'Удаление');
                                mgs.all.addClass('hidden');
                                break;
                        }
                    },
                    close: function(){
                        mgs.all.val('').removeClass('ui-state-error');
                        mgs.all
                            .add(  form.find('.errorLog').empty()  )
                            .add(  form.find('fieldset')  )
                            .removeClass('hidden');
                        mgsActionInit(Elm.mgsGrid);
                        mgsDirectInit(Elm.mgsGrid);
                    }

        }).removeClass('hidden');

        dlg.submit(function(e){
                var data   = {},
                    a      = form.data('a');
         
                switch (form.data('action')) {
                    case 'insert':
                        data = {
                              action:     '<?php echo ACTIONS::MESSAGES_INSERT; ?>',
                              title:      mgs.title.val(),
                              to_date:    mgs.to_date.val(),
                              text:       mgs.text.val(),
                              viewable:   1,
                              type:       0
                        };
                        break;
                    case 'update':
                        data = {
                              action:     '<?php echo ACTIONS::MESSAGES_UPDATE; ?>',
                              id:         Number(a.id),
                              title:      mgs.title.val(),
                              to_date:    mgs.to_date.val(),
                              text:       mgs.text.val(),
                              viewable:   Number(a.viewable),
                              type:       Number(a.type)
                        };
                        break;
                    case 'delete':
                        data = {
                              action:     '<?php echo ACTIONS::MESSAGES_DELETE; ?>',
                              id:         Number(a.id)
                        };
                        break;
                }
                if (data != null) {
                jsonRequest('messages.php', data, function(data){
                            if(!checkSession(data)) { Elm.loginFormModal.dialog('open'); return false; }
                            var response = data.response_data;
                            if (response.errorLog) { $('.errorLog').append($(response.errorLog)); return; }
                            switch (form.data('action')) {
                                case 'update':
                                    $('.message'+response.id).replaceWith(  renderMessage(response)  );
                                    dlg.dialog('close');
                                    break;

                                case 'insert':
                                    $('.messages[data-page="1"]').prepend(renderMessage(response));
                                    dlg.dialog('close');
                                    break;

                                case 'delete':
                                    $('.message'+response.id).remove();;
                                    dlg.dialog('close');
                                    break;
                          }
                          
                    },
                    function(data){ console.error(data.message) }
                );
                }
        });
        form.find('button[type="reset"]').click(function(){
            dlg.dialog('close');
        });
        $('a[data-action]').each(function(){
                $(this).click(function(e){
                    form.data({
                        action: $(this).data('action'),
                        a:      $(this).parents('li').data()
                    });
                    dlg.dialog('open');
                });
        });
    }
    $(function() {
        form.find('*[name=to_date]').datepicker();
        form.find('*[name=to_date]').datepicker('option', 'dateFormat', 'yy-mm-dd');
    });
    
</script>
